﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json.Linq;
using SysFrame.BP;
using SysFrame.Message;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppServer.Controllers
{
    public class SysPageFilte : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string Token = filterContext.HttpContext.Request.Headers["Authorization"];
            string path = filterContext.HttpContext.Request.Path;
            string body = QueryString(filterContext.HttpContext.Request);
            //任何页面都判断body 转json 和 Action MenuId 字段是否存在 
            //   如果错误返回"参数错误" code 5001
            //判断Token
            //  如果是登录页面，就不判断Token了
            //  非登录页，Token转用户 和 MenuId比对（MenuId=-1就不对比了），
            //    如果用户错误 返回" 重新登录 " code 5002
            //    如果没权限 返回" 访问权限错误 " code 5003
            MsReturned res = new MsReturned();
            if (!string.IsNullOrEmpty(body))
            {
                try
                {
                    //任何页面都判断body 转json 和 Action MenuId 字段是否存在 
                    JObject form = JObject.Parse(body);
                    string Action = form["Action"].ToString();
                    string MenuId = form["MenuId"].ToString();
                    if (string.IsNullOrEmpty(Action) || string.IsNullOrEmpty(MenuId))
                    {
                        res.strMsId = "5001";
                        res.strMS = "请求参数错误；";
                        filterContext.Result = new ContentResult()
                        {
                            Content = JObject.FromObject(res).ToString(),
                        };
                        //filterContext.HttpContext.Response.StatusCode = Convert.ToInt32(res.strMsId);
                    }
                    //判断Token System1和Login
                    if (path.IndexOf("System1") < 0 || Action != "Login")
                    {
                        if (!string.IsNullOrEmpty(Token))
                        {
                            try
                            {
                                //成功获取用户
                                string login = EncryptDES.strEncryptByDES(Token);
                                Mssystem_1 ms1 = new Mssystem_1();
                                ms1 = Mssystem_1.parse(JObject.Parse(login));
                                filterContext.HttpContext.Session.SetString("LoginUser", login);
                            }
                            catch(Exception ex)
                            {
                                res.strMsId = "5002";
                                res.strMS = "请重新登录；";
                                filterContext.Result = new ContentResult()
                                {
                                    Content = JObject.FromObject(res).ToString(),
                                };
                            }
                        }
                        else
                        {
                            res.strMsId = "5002";
                            res.strMS = "请重新登录；";
                            filterContext.Result = new ContentResult()
                            {
                                Content = JObject.FromObject(res).ToString(),
                            };
                        }
                    }

                }
                catch { }
            }
            else
            {
                res.strMsId = "5001";
                res.strMS = "请求参数错误；";
                filterContext.Result = new ContentResult()
                {
                    Content = JObject.FromObject(res).ToString(),
                };
                filterContext.HttpContext.Response.StatusCode = Convert.ToInt32(res.strMsId);
            }
            base.OnActionExecuting(filterContext);
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
        }

        /// <summary>
        ///  根据请求信息返回请求串
        /// </summary>
        /// <param name="request">请求信息</param>
        /// <returns>请求串</returns>
        public static string QueryString(HttpRequest request)
        {
            string text = "";
            using (var ms = new MemoryStream())
            {
                request.Body.Seek(0, 0);
                request.Body.CopyTo(ms);
                var b = ms.ToArray();
                var postParamsString = Encoding.UTF8.GetString(b);
                text = postParamsString.ToString();
            }
            return text;
        }
    }
    public class SysPageError : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            HttpRequest request = filterContext.HttpContext.Request;
            Exception exception = filterContext.Exception;
            //异常是否处理
            if (filterContext.ExceptionHandled == true)
            {
                return;
            }
            filterContext.HttpContext.Response.StatusCode = 200;
            //下面进行异常处理的逻辑，可以记录日志、返回前端友好提示等
            MsReturned res = new MsReturned();
            res.strMsId = "5004";
            res.MsRbool = false;
            res.strMS = "服务器异常：请求参数错误";
            filterContext.Result = new ContentResult()
            {
                Content = JObject.FromObject(res).ToString(),
            };

            //设置异常已经处理,否则会被其他异常过滤器覆盖
            filterContext.ExceptionHandled = true;
        }
    }
}
